// 云函数入口文件
const cloud = require('wx-server-sdk')
const tencentcloud = require("tencentcloud-sdk-nodejs");
cloud.init()

function TXCloud_init(secretId,secretKey,url){
  const OcrClient = tencentcloud.ocr.v20181119.Client;
  const models = tencentcloud.ocr.v20181119.Models;
  const Credential = tencentcloud.common.Credential;
  const ClientProfile = tencentcloud.common.ClientProfile;
  const HttpProfile = tencentcloud.common.HttpProfile;
  let cred = new Credential(secretId, secretKey);
  let httpProfile = new HttpProfile();
  httpProfile.endpoint = "ocr.tencentcloudapi.com";
  let clientProfile = new ClientProfile();
  clientProfile.httpProfile = httpProfile;
  let client = new OcrClient(cred, "ap-guangzhou", clientProfile);
  let req = new models.IDCardOCRRequest();
  // 参数设置
  let config = `,"Config":"{\\"CropIdCard\\":true,\\"CropPortrait\\":true,\\"CopyWarn\\":true,\\"BorderCheckWarn\\":true,\\"ReshootWarn\\":true,\\"DetectPsWarn\\":true,\\"TempIdWarn\\":true,\\"InvalidDateWarn\\":true}"`

  let params = `{"ImageUrl":"${url}","CardSide":"FRONT"${config}}`
  req.from_json_string(params);

  return new Promise((resolve, reject) => {
    client.IDCardOCR(req, function (errMsg, response) {
      if (errMsg) {
        reject(errMsg)
        return;
      }
      let res = JSON.parse(response.to_json_string())
      res.AdvancedInfo = JSON.parse(res.AdvancedInfo)
      resolve(res)
    });
  })
}

// 云函数入口函数
exports.main = async (event, context) => {
  // 获取临时链接evnet.url
  let url = event.url

  return TXCloud_init(event.secretId, event.secretKey,url)
}
